import { IPublicTypeJSExpression } from '@alilc/lowcode-types';

import {
  BuilderComponentPlugin, NodeGeneratorConfig, ICodeStruct, ChunkType, IScope,
  BuilderComponentPluginFactory, IContainerInfo, HandlerSet, FileType,
} from '../../../types';
import { REACT_CHUNK_NAME } from './const';
import { createReactNodeGenerator } from '../../../utils/nodeToJSX';
import { Scope } from '../../../utils/Scope';
import { generateExpression } from '../../../utils/jsExpression';
import { transformJsExpr } from '../../../core/jsx/handlers/transformJsExpression';
import { transformThis2Context } from '../../../core/jsx/handlers/transformThis2Context';
import { generateCompositeType } from '../../../utils/compositeType';

export interface PluginConfig {
  fileType?: string;
  nodeTypeMapping?: Record<string, string>;
}

const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
  const cfg = {
    fileType: FileType.JSX,
    // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
    nodeTypeMapping: {} as Record<string, string>,
    ...config,
  };
  const { nodeTypeMapping } = cfg;
  const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
    const next: ICodeStruct = {
      ...pre,
    };
    const { tolerateEvalErrors = true} = next.contextData;
    // 这里会将内部的一些子上下文的访问(this.xxx)转换为 __$$context.xxx 的形式
    const customHandlers: HandlerSet<string> = {
      expression(input: IPublicTypeJSExpression, scope: IScope, config) {
        return transformJsExpr(generateExpression(input, scope), scope, {
          dontWrapEval: !tolerateEvalErrors,
          dontTransformThis2ContextAtRootScope: true,
        });
      },
      function(input, scope: IScope) {
        return transformThis2Context(
          generateCompositeType(
            { type: 'JSFunction', value: input.value || 'function () {}'},
            Scope.createRootScope()
          ),
          scope,
          { ignoreRootScope: true },
        );
      },
    };

    const generatorPlugins: NodeGeneratorConfig = {
      handlers: customHandlers,
      tagMapping: (v) => nodeTypeMapping[v] || v,
      tolerateEvalErrors,
    };
    const generator = createReactNodeGenerator(generatorPlugins);
    const ir = next.ir as IContainerInfo;
    const scope: IScope = Scope.createRootScope();
    const jsxContent = generator(ir, scope);
    // JSX 的内容
    next.chunks.push({
      type: ChunkType.STRING,
      fileType: cfg.fileType,
      name: REACT_CHUNK_NAME.ClassRenderJSX,
      content: `
        const __$$context = this._context || this;
        const { state } = __$$context;

        return ${jsxContent};
      `,
      linkAfter: [REACT_CHUNK_NAME.ClassRenderStart, REACT_CHUNK_NAME.ClassRenderPre],
    });
    return next;
  };
  return plugin;
};

export default pluginFactory;
